const fs = require('fs');

const updateFile = (api, file, callback) => {
  file = api.resolve(file);
  let content = fs.existsSync(file)
    ? fs.readFileSync(file, { encoding: 'utf8' })
    : '';

  content = callback(content.split(/\r?\n/g)).join('\n');

  fs.writeFileSync(file, content, {
    encoding: 'utf8',
  });
};

const genHtml = (api) => {
  updateFile(api, './public/index.html', (lines) => {
    const htmlIndex = lines.findIndex((line) => line.match(/favicon.ico/));

    if (htmlIndex !== -1) {
      lines[htmlIndex] = lines[htmlIndex].replace(
        /favicon.ico/,
        '<%= BASE_URL %>favicon.ico'
      );
    }

    return lines;
  });
};

module.exports = genHtml;
